package com.ktjy.ktmall.servlet;

import cn.hutool.json.JSONUtil;
import com.ktjy.ktmall.entity.AjaxResult;
import com.ktjy.ktmall.service.TMenuService;
import com.ktjy.ktmall.service.impl.TMenuServiceImpl;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "MenuServlet", urlPatterns = "/uni/menu")
public class MenuServlet extends HttpServlet {
    private TMenuService service = null;

    public void init(ServletConfig config) throws ServletException {
        service = new TMenuServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleRequest(req, resp);
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleRequest(req, resp);
    }

    private void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置响应内容类型
        resp.setContentType("application/json;charset=UTF-8");
        // 设置CORS支持
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        resp.setHeader("Access-Control-Allow-Headers", "x-requested-with, content-type");

        if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        // 创建PrintWriter对象
        PrintWriter out = resp.getWriter();
        AjaxResult result = AjaxResult.success("获取数据成功");
        result.setResult(service.getMenus());
        String jsonStr = JSONUtil.toJsonStr(result);
        out.println(jsonStr);

        System.out.println(jsonStr);
        out.flush();
        out.close();
    }
}